//
//  ZTResultViewController.m
//  徙游记-01
//
//  Created by hcios on 2017/7/8.
//  Copyright © 2017年 鹿林. All rights reserved.
//
#import "ZTResultViewController.h"
#import "MoveDetailModel.h"
#import "MoveDetailFrameModel.h"
#import "MoveDetailTableViewCell.h"
#import "UIImageView+WebCache.h"

#import "MoveHeaderView.h"
#import "XLPhotoBrowser.h"
#import "XYJHeaderModel.h"
#import "UIView+XLExtension.h"

//分享
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "ZYShareItem.h"
#import "ZYShareView.h"

//跳转
#import "XYJLXResultViewController.h"
#import "UserViewController.h"


@interface ZTResultViewController ()<UITableViewDelegate,UITableViewDataSource,XLPhotoBrowserDelegate,XLPhotoBrowserDatasource,MoveDetailTableViewCellDelegate>{
    
    NSMutableArray *_dataArr;
    
    UITableView *_tableView;
    
    NSString *header_name;
    
    NSString *header_title;
    
    NSString *header_imageUrl;
    
    //HeaderView
    MoveHeaderView *header;
    
    
    //返回顶部按钮
    UIButton * topButton;
    NSIndexPath *_indexPath;
    NSMutableArray *_dataUrlArray;
    NSMutableArray *_dataImageViewArray;
    
    //顶部button
    UIButton * returnButton;
    
    UIButton * shareButton;
    
}

@end

@implementation ZTResultViewController

-(instancetype)init{
    if (self = [super init]) {
        _dataArr = [[NSMutableArray alloc] init];
        _dataUrlArray = [[NSMutableArray alloc] init];
        _dataImageViewArray = [[NSMutableArray alloc] init];
        _indexPath = [[NSIndexPath alloc] init];
    }
    return self;
}

#pragma mark - 生命周期
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //初始化主table
    [self initTable];
    //初始化按钮
    [self setupTopButton];
    //网络请求
    [self netWorking];
    //从屏幕顶端开始加载
    self.automaticallyAdjustsScrollViewInsets = NO;
    
}

#pragma mark - 初始化按钮
-(void) setupTopButton{
    
    topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [topButton setFrame:CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 100, 50, 50)];
    topButton.layer.cornerRadius = 25;
    topButton.layer.masksToBounds = YES;
    [topButton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [topButton setImage:[UIImage imageNamed:@"back_top"] forState:UIControlStateNormal];
    [topButton.titleLabel setFont:[UIFont systemFontOfSize:11]];
    topButton.hidden = YES;
    [self.view addSubview:topButton];
    [topButton bringSubviewToFront:_tableView];
    
    //returnButton
    returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [returnButton setFrame:CGRectMake(10, 20, 50, 50)];
    returnButton.layer.cornerRadius = 25;
    returnButton.layer.masksToBounds = YES;
    returnButton.alpha = 0.618;
    returnButton.backgroundColor = [UIColor blackColor];
    [returnButton setImage:[UIImage imageNamed:@"homepage_back_icon03"] forState:UIControlStateNormal];
    [returnButton addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnButton];
    [self.view bringSubviewToFront:returnButton];
    
    
    //shareButton
    shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setFrame:CGRectMake(SCREEN_WIDTH - 60, 20, 50, 50)];
    shareButton.layer.cornerRadius = 25;
    shareButton.layer.masksToBounds = YES;
    shareButton.alpha = 0.618;
    shareButton.backgroundColor = [UIColor blackColor];
    [shareButton setImage:[UIImage imageNamed:@"homepage_message_icon03"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    [self.view bringSubviewToFront:shareButton];
    
}

#pragma mark - 点击事件
//返回上一页
- (void) returnBack{
    
    NSLog(@"点击");
    [[self navigationController]popViewControllerAnimated:YES];
}
//返回顶部
- (void)click{
    [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    topButton.hidden = YES;
}

//分享
- (void) share{
    
    __weak typeof(self) weakSelf = self;
    ZYShareItem *itemWeiXin = [ZYShareItem itemWithTitle:@"微信好友" icon:@"wechat-icon" handler:^{
        [weakSelf shareWebToWechat];
        NSLog(@"分享");
    }];
    
    NSArray *arr = @[itemWeiXin];
    ZYShareView *share = [ZYShareView shareViewWithShareItems:arr functionItems:nil];
    [share show];
}

-(void)initTable{
    _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:_tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MoveDetailTableViewCell *cell = [MoveDetailTableViewCell cellWithTableView:tableView];
    cell.frameModel = _dataArr[indexPath.row];
    cell.delegate = self;
    
    return cell;
}



#pragma mark - UITableViewDelegate
//添加headerView
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    header = [[MoveHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 270)];
    //赋值
    header.header_nameLab.text = header_name;
    header.header_titleLab.text = header_title;
    [header.headImageView sd_setImageWithURL:[NSURL URLWithString:header_imageUrl] placeholderImage:nil];
    header.headImageView.contentMode = UIViewContentModeScaleAspectFill;
    return header;
    
}

//设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MoveDetailFrameModel * frameModel = _dataArr[indexPath.row];
    return frameModel.cellHeight;
}

//设置Header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 270;
    }else return CGFLOAT_MIN;
}


-(void)netWorking{
    
    NSString *urlString = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%@.json",_userID];
    
    //网络请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSMutableArray * resultArr = [[NSMutableArray alloc]init];
        resultArr = responseObject[@"article_sections"];
        //取出headerView先关数据
        XYJHeaderModel * model = [[XYJHeaderModel alloc] initWithDict:responseObject];
        header_title = model.header_title;
        header_name = model.header_name;
        header_imageUrl = model.header_image_url;
        if (resultArr) {
            //遍历
            for (NSDictionary * dict in resultArr) {
                //取地名
                NSMutableDictionary * resultDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
                //拼接
                if (resultDict[@"attraction"]) {
                    [resultDict setObject:dict[@"attraction"][@"id"] forKey:@"id"];
                    [resultDict setObject:dict[@"attraction"][@"name"] forKey:@"name"];
                }
                //取值
                MoveDetailModel * model = [[MoveDetailModel alloc] initWithDict:resultDict];
                model.description_user_ids = resultDict[@"description_user_ids"];
                MoveDetailFrameModel * frameModel = [[MoveDetailFrameModel alloc] init];
                frameModel.model = model;
                [_dataArr addObject:frameModel];
                [_dataUrlArray addObject:model.image_url];
                //取出图片
                UIImageView * imageView = [[UIImageView alloc] init];
                [imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
                [_dataImageViewArray addObject:imageView];
            }
            [_tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络请求失败");
    }];
}

//上滑隐藏，下滑显示
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if (velocity.y > 0) {
        topButton.hidden = NO;
    }
}


#pragma mark - ScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    if (point.y < 0) {
        CGRect rect = header.headImageView.frame;
        rect.origin.y = point.y;
        rect.size.height = -point.y + 270;
        header.headImageView.frame = rect;
    }
}


#pragma mark - cell的代理方法
//点击地名的方法
//-(void)clickButtonLabel:(UITapGestureRecognizer *)tap{
//    //获取点击图片的indexRow
//    UIImageView *img = (UIImageView *)tap.view;
//    CGPoint point = img.center;
//    point = [_tableView convertPoint:point fromView:img.superview];
//    NSIndexPath * index = [_tableView indexPathForRowAtPoint:point];
//    MoveDetailFrameModel * frameModel = _dataArr[index.row];
//    XYJLXResultViewController * VC = [[XYJLXResultViewController alloc] init];
//    VC.selfID = frameModel.model.selfID;
//    [self.navigationController pushViewController:VC animated:YES];
//}


//作者的点击方法
-(void)clickUserToVC:(NSString *)stringID{
    UserViewController * VC = [[UserViewController alloc] init];
    VC.userID = stringID;
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)clicks:(UITapGestureRecognizer *)tap{
    NSLog(@"点击图片");
    //获取点击图片的indexpath
    UIImageView *img = (UIImageView *)tap.view;
    CGPoint point = img.center;
    point = [_tableView convertPoint:point fromView:img.superview];
    _indexPath = [_tableView indexPathForRowAtPoint:point];
    
    // 快速创建并进入浏览模式
    XLPhotoBrowser * browser = [XLPhotoBrowser showPhotoBrowserWithCurrentImageIndex:_indexPath.row imageCount:_dataUrlArray.count datasource:self];
    browser.delegate = self;
    //隐藏小圆点
    browser.showPageControl = NO;
    browser.pageControlStyle = XLPhotoBrowserPageControlStyleNone;
    // 设置长按手势弹出的地步ActionSheet数据,不实现此方法则没有长按手势
    [browser setActionSheetWithTitle:@"" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",@"发送给朋友",nil];
    
}



#pragma mark    -   XLPhotoBrowserDatasource
-(UIImage *)photoBrowser:(XLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return nil;
}


-(UIView *)photoBrowser:(XLPhotoBrowser *)browser sourceImageViewForIndex:(NSInteger)index{
    //返回指定位置
    [self returnTableViewCellWithIndex:index];
    return _dataImageViewArray[index];
}


-(void)returnTableViewCellWithIndex:(NSInteger)index{
    NSLog(@"点击图片消失");
    NSIndexPath *selfIndexPath = [NSIndexPath indexPathForRow:index inSection:_indexPath.section];
    [_tableView scrollToRowAtIndexPath:selfIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


-(NSURL *)photoBrowser:(XLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    return [NSURL URLWithString:_dataUrlArray[index]];
}



#pragma mark    -   XLPhotoBrowserDelegate
-(void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex{
    switch (actionSheetindex) {
        case 0:     //保存
        {
            NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
            [browser saveCurrentShowImage];
        }
            break;
        case 1:     //发送给朋友
        {
            NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
            NSLog(@"点击收藏");
            [self shareIconToWechat:currentImageIndex];
        }
            break;
        default:
        {
            NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
        }
            break;
    }
}


#pragma mark - 分享
//分享网络链接
-(void)shareWebToWechat{
    //创建分享对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //url转换成NSData(如果直接使用无法获取)
    NSString *urlString = _backImgUrl;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"小仙女推荐精品游戏:%@",_nameText] descr:@"Cx" thumImage:[UIImage imageWithData:data]];
    
    //设置网页
    shareObject.webpageUrl = [NSString stringWithFormat:@"http://chanyouji.com/trips/%@?from=groupmessage&isappinstalled=1",_selfID];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            NSLog(@"***********Share fail with error %@***********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}





//分享图片链接
- (void)shareIconToWechat:(NSInteger)currentImageIndex{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    [shareObject setShareImage:[_dataImageViewArray[currentImageIndex] image]];
    //    [shareObject setShareImage:[imageView image]];
    
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}

@end
